package com.sdyeda.readiot.tools;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;

import org.springframework.scheduling.support.CronExpression;

public class TimeTools {

	// 取得任务下次执行时间
	@SuppressWarnings("null")
	public static Date NextTaskTime(String type, String cron, Long delay, Date begin) {
		Date nextTime;

		if (type.equals("cron")) {
			LocalDateTime local = CronExpression.parse(cron).next(LocalDateTime.now());
			nextTime = Date.from(local.atZone(ZoneId.systemDefault()).toInstant());
		} else {
			Calendar cld = Calendar.getInstance();
			cld.setTime(begin);
			cld.add(Calendar.SECOND, (int) (delay / 1000));
			nextTime = cld.getTime();
		}
		return nextTime;
	}

	// 计算时间间隔
	public static String getDatePoor(Date endDate, Date nowDate) {

		long nd = 1000 * 24 * 60 * 60;
		long nh = 1000 * 60 * 60;
		long nm = 1000 * 60;
		long ns = 1000;
		// 获得两个时间的毫秒时间差异
		long diff = endDate.getTime() - nowDate.getTime();
		if(diff<0) diff=0;
		// 计算差多少天
		long day = diff / nd;
		// 计算差多少小时
		long hour = diff % nd / nh;
		// 计算差多少分钟
		long min = diff % nd % nh / nm;
		// 计算差多少秒//输出结果
		long sec = diff % nd % nh % nm / ns;
		return String.format("%02d天%02d时%02d分%02d秒", day, hour, min, sec);
	}

	// 计算时间间隔
	public static String getDatePoorShort(Date endDate, Date nowDate) {

		long nd = 1000 * 24 * 60 * 60;
		long nh = 1000 * 60 * 60;
		long nm = 1000 * 60;
		long ns = 1000;
		// 获得两个时间的毫秒时间差异
		long diff = endDate.getTime() - nowDate.getTime();
		if(diff<0) diff=0;
		// 计算差多少天
		long day = diff / nd;
		// 计算差多少小时
		long hour = diff % nd / nh;
		// 计算差多少分钟
		long min = diff % nd % nh / nm;
		// 计算差多少秒//输出结果
		long sec = diff % nd % nh % nm / ns;

		String result = String.format("%02d分%02d秒", min, sec);
		if (hour != 0 || day != 0) {
			result = String.format("%02d时%s", hour, result);
		}
		if (day != 0) {
			result = String.format("%02d天%s", day, result);
		}
		return result;
	}

}
